import { ModernBaseService } from '../service/base/ModernBaseService';
import { Item } from '../shared/face';

// 市场商品接口
export interface MarketItem {
    _id: string;
    item: Item;
    put_id: string; // 上架者ID
    put_time: number; // 上架时间
    sell_price: number; // 售价
    status: 'on_sale' | 'sold' | 'expired';
}

// 市场日志接口
export interface MarketLog {
    _id: string;
    item_id: string;
    buyer_id: string;
    seller_id: string;
    price: number;
    trade_time: number;
    item_name: string;
}

/**
 * 市场仓储类 - 负责市场数据的访问与缓存
 */
export class MarketRepository extends ModernBaseService {
    private marketItems = new Map<string, MarketItem>();
    private marketLogs = new Map<string, MarketLog>();
    private pendingItems = new Map<string, MarketItem>(); // 待存储的商品
    private pendingLogs = new Map<string, MarketLog>(); // 待存储的日志
    private pendingUpdates = new Map<string, Partial<MarketItem>>(); // 待更新的商品
    private initialized = false;

    constructor(container?: any) {
        super(container);
    }

    /**
     * 初始化市场数据
     */
    async initialize(): Promise<void> {
        if (this.initialized) {
            return;
        }

        try {
            this.log('正在初始化市场数据...');
            
            // 加载市场数据到内存
            await this.loadMarketData();
            
            // 加载交易日志到内存
            await this.loadMarketLogs();
            
            this.initialized = true;
            this.log(`市场管理器初始化完成，加载了 ${this.marketItems.size} 个商品，${this.marketLogs.size} 条交易记录`);
        } catch (error) {
            this.log('市场管理器初始化失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    /**
     * 加载市场数据到内存
     */
    private async loadMarketData(): Promise<void> {
        try {
            const data = await this.sdk.db.find('market_items');
            this.marketItems.clear();
            data.forEach((item: any) => {
                if (item.status === 'on_sale') {
                    this.marketItems.set(item._id, item);
                }
            });
            this.log(`加载了 ${this.marketItems.size} 个在售商品到内存`);
        } catch (error) {
            this.log('加载市场数据失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    /**
     * 加载市场日志到内存
     */
    private async loadMarketLogs(): Promise<void> {
        try {
            const data = await this.sdk.db.find('market_logs');
            this.marketLogs.clear();
            data.forEach((log: any) => {
                this.marketLogs.set(log._id, log);
            });
            this.log(`加载了 ${this.marketLogs.size} 条交易记录到内存`);
        } catch (error) {
            this.log('加载市场日志失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    /**
     * 保存市场数据到数据库
     */
    async save(): Promise<void> {
        try {
            // 批量存储待存储的商品
            if (this.pendingItems.size > 0) {
                const itemsToInsert: MarketItem[] = Array.from(this.pendingItems.values());
                if (itemsToInsert.length > 0) {
                    await this.sdk.db.getCollection('market_items').insertMany(itemsToInsert as any);
                    this.log(`批量存储了 ${itemsToInsert.length} 个商品到数据库`);
                }
                this.pendingItems.clear();
            }

            // 批量存储待存储的日志
            if (this.pendingLogs.size > 0) {
                const logsToInsert: MarketLog[] = Array.from(this.pendingLogs.values());
                if (logsToInsert.length > 0) {
                    await this.sdk.db.getCollection('market_logs').insertMany(logsToInsert as any);
                    this.log(`批量存储了 ${logsToInsert.length} 条交易记录到数据库`);
                }
                this.pendingLogs.clear();
            }

            // 批量更新商品状态
            if (this.pendingUpdates.size > 0) {
                for (const [itemId, updateData] of this.pendingUpdates.entries()) {
                    await this.sdk.db.update('market_items', { _id: itemId }, updateData);
                }
                this.log(`批量更新了 ${this.pendingUpdates.size} 个商品状态`);
                this.pendingUpdates.clear();
            }

            this.log('市场数据保存完成');
        } catch (error) {
            this.log('保存市场数据失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    /**
     * 上架商品到内存
     */
    async putItemOnSale(item: Item, price: number, sellerId: string): Promise<string> {
        await this.ensureInitialized();
        this.validateRequiredParams({ item, price, sellerId }, ['item', 'price', 'sellerId']);

        try {
            const marketItem: MarketItem = {
                _id: this.sdk.tool.common.uuid,
                item: item,
                put_id: sellerId,
                put_time: Date.now(),
                sell_price: price,
                status: 'on_sale'
            };

            // 存储到内存
            this.marketItems.set(marketItem._id, marketItem);

            // 添加到待存储队列
            this.pendingItems.set(marketItem._id, marketItem);

            this.log(`物品上架: ${item.name} 价格: ${price}`);
            return marketItem._id;
        } catch (error) {
            this.log('上架商品失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    /**
     * 记录交易日志到内存
     */
    async recordTrade(item: MarketItem, buyerId: string, sellerId: string, price: number): Promise<string> {
        await this.ensureInitialized();
        this.validateRequiredParams({ item, buyerId, sellerId, price }, ['item', 'buyerId', 'sellerId', 'price']);

        try {
            const logId = `${item._id}_${Date.now()}`;
            const log: MarketLog = {
                _id: logId,
                item_id: item._id,
                buyer_id: buyerId,
                seller_id: sellerId,
                price: price,
                trade_time: Date.now(),
                item_name: item.item.name
            };

            // 存储到内存
            this.marketLogs.set(logId, log);

            // 添加到待存储队列
            this.pendingLogs.set(logId, log);

            this.log(`记录交易日志: ${item.item.name} 买家: ${buyerId} 卖家: ${sellerId}`);
            return logId;
        } catch (error) {
            this.log('记录交易日志失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    /**
     * 从市场移除商品（减少数量或完全移除）
     */
    async removeFromMarket(itemId: string, count: number): Promise<boolean> {
        await this.ensureInitialized();
        this.validateRequiredParams({ itemId, count }, ['itemId', 'count']);

        try {
            const item = this.marketItems.get(itemId);
            if (!item) {
                this.log(`商品不存在: ${itemId}`, 'warn');
                return false;
            }

            // 减少商品数量
            item.item.count -= count;
            
            // 如果商品数量为0或负数，则从市场移除
            if (item.item.count <= 0) {
                // 更新状态为已售出
                item.status = 'sold';
                
                // 添加到待更新队列
                this.pendingUpdates.set(itemId, { status: 'sold' });
                
                // 从内存中移除
                this.marketItems.delete(itemId);
                
                this.log(`商品 ${item.item.name} 已售罄，从市场移除`);
            } else {
                // 商品还有剩余，更新数量
                this.pendingUpdates.set(itemId, { 
                    item: item.item 
                });
                
                this.log(`商品 ${item.item.name} 剩余数量: ${item.item.count}`);
            }

            return true;
        } catch (error) {
            this.log('从市场移除商品失败: ' + (error as any).message, 'error');
            return false;
        }
    }

    /**
     * 下架商品
     */
    async takeOffSale(itemId: string, sellerId: string): Promise<boolean> {
        await this.ensureInitialized();
        this.validateRequiredParams({ itemId, sellerId }, ['itemId', 'sellerId']);

        try {
            const item = this.marketItems.get(itemId);
            if (!item) {
                this.log(`商品不存在: ${itemId}`, 'error');
                return false;
            }

            if (item.put_id !== sellerId) {
                this.log(`商品不属于卖家: ${itemId}`, 'error');
                return false;
            }

            // 更新状态为已过期
            item.status = 'expired';

            // 添加到待更新队列
            this.pendingUpdates.set(itemId, { status: 'expired' });

            // 从内存中移除
            this.marketItems.delete(itemId);

            this.log(`商品下架成功: ${itemId}`);
            return true;
        } catch (error) {
            this.log('下架商品失败: ' + (error as any).message, 'error');
            return false;
        }
    }

    /**
     * 获取市场商品列表
     */
    async getMarketItems(): Promise<MarketItem[]> {
        await this.ensureInitialized();
        return Array.from(this.marketItems.values());
    }

    /**
     * 获取市场日志
     */
    async getMarketLogs(): Promise<MarketLog[]> {
        await this.ensureInitialized();
        return Array.from(this.marketLogs.values());
    }

    /**
     * 获取商品信息
     */
    async getItemInfo(itemId: string): Promise<MarketItem | undefined> {
        await this.ensureInitialized();
        this.validateRequiredParams({ itemId }, ['itemId']);
        
        const item = this.marketItems.get(itemId);
        if (item) {
            this.log(`获取商品信息: ${item.item.name} (ID: ${itemId})`);
        } else {
            this.log(`商品不存在: ${itemId}`, 'warn');
        }
        
        return item;
    }

    /**
     * 按条件搜索市场商品
     */
    async searchMarketItems(criteria: {
        sellerId?: string;
        minPrice?: number;
        maxPrice?: number;
        itemType?: string;
        itemName?: string;
    }): Promise<MarketItem[]> {
        await this.ensureInitialized();
        
        const allItems = Array.from(this.marketItems.values());
        
        const filtered = allItems.filter(item => {
            if (criteria.sellerId && item.put_id !== criteria.sellerId) return false;
            if (criteria.minPrice !== undefined && item.sell_price < criteria.minPrice) return false;
            if (criteria.maxPrice !== undefined && item.sell_price > criteria.maxPrice) return false;
            if (criteria.itemType && item.item.type.toString() !== criteria.itemType) return false;
            if (criteria.itemName && !item.item.name.includes(criteria.itemName)) return false;
            
            return true;
        });
        
        this.log(`市场商品搜索结果: ${filtered.length} 个商品符合条件`);
        return filtered;
    }

    /**
     * 获取市场统计信息
     */
    async getMarketStats(): Promise<{
        totalItems: number;
        totalTransactions: number;
        averagePrice: number;
        topSellers: Array<{ sellerId: string; itemCount: number }>;
        recentTransactions: MarketLog[];
    }> {
        await this.ensureInitialized();
        
        const items = Array.from(this.marketItems.values());
        const logs = Array.from(this.marketLogs.values());
        
        // 计算平均价格
        const totalPrice = items.reduce((sum, item) => sum + item.sell_price, 0);
        const averagePrice = items.length > 0 ? totalPrice / items.length : 0;
        
        // 统计销售者
        const sellerStats = new Map<string, number>();
        items.forEach(item => {
            const count = sellerStats.get(item.put_id) || 0;
            sellerStats.set(item.put_id, count + 1);
        });
        
        const topSellers = Array.from(sellerStats.entries())
            .map(([sellerId, itemCount]) => ({ sellerId, itemCount }))
            .sort((a, b) => b.itemCount - a.itemCount)
            .slice(0, 10);
        
        // 最近的交易记录
        const recentTransactions = logs
            .sort((a, b) => b.trade_time - a.trade_time)
            .slice(0, 20);
        
        const stats = {
            totalItems: items.length,
            totalTransactions: logs.length,
            averagePrice,
            topSellers,
            recentTransactions
        };
        
        this.log('市场统计信息已生成');
        return stats;
    }

    /**
     * 确保已初始化
     */
    protected async ensureInitialized(): Promise<void> {
        if (!this.initialized) {
            await this.initialize();
        }
    }
}
